<?php
/**
 * @title 78. 子集 - 二进制+正反互补
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer[][]
     */
    function subsets($nums) {
        /**
         * @since 2020-08-07 结果集
         */
        $result = [];

        /**
         * @since 2020-08-07 长度
         */
        $len = count($nums);

        /**
         * @since 2020-08-07 按位获取, 对半
         */
        for($i=0, $iMax=pow(2, $len-1)-1; $i<=$iMax; $i++){
            $bin = strval(decbin($i));
            $binLen = strlen($bin);

            /**
             * @since 2020-08-07 空位补0的数量
             */
            $k = $len-$binLen;

            /**
             * @since 2020-08-07 正反互补
             */
            $arr1 = [];
            $arr2 = array_slice($nums, 0, $k);

            /**
             * @since 2020-08-07 按位取值
             */
            for ($j=0; $j<$binLen; $j++, $k++){
                if($bin[$j] == 1){
                    $arr1[] = $nums[$k];
                } else {
                    $arr2[] = $nums[$k];
                }
            }

            /**
             * @since 2020-08-07 赋值
             */
            $result[] = $arr1;
            $result[] = $arr2;
        }

        /**
         * @return
         */
        return $result;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.07_4.php
 */
$datas = [
    [1],
    // [1,2,3],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->subsets($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
